import requests
import json
import time
import pymysql
import redis
from quote_folder.Db_connect import DB_connect

db = DB_connect().online_big_data()
cur = db.cursor()
inst = "XH"


def get_patent_status(session, authorization, application_number, redis_con):
    status_post_url = r'https://cpquery.cponline.cnipa.gov.cn/api/view/gn/sqxx'
    headers = {'Accept': 'application/json, text/plain, */*',
               'Accept-Encoding': 'gzip, deflate, br',
               'Accept-Language': 'zh-CN,zh;q=0.9',
               'Authorization': '%s' % authorization,
               'Connection': 'keep-alive',
               'Content-Length': '30',
               'Content-Type': 'application/json;charset=UTF-8',
               'Cookie': '_gscu_1382584180=69285472xdmfc499; _trs_uv=ld1d1zch_4693_f4w3; dX1xbeyMT58WO=5ht7IWrUfLNNB1bsyXg3hCcIHuwvIbDXWpqKbggLWkZ9VwNPvCErPwxkJpAEErTaT486BpeXZ_TpcV4Db_QKoCa',
               'Host': 'cpquery.cponline.cnipa.gov.cn',
               'Origin': 'https://cpquery.cponline.cnipa.gov.cn',
               'Referer': 'https://cpquery.cponline.cnipa.gov.cn/detail/index?zhuanlisqh=%s&anjianbh' % application_number,
               'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
               'sec-ch-ua-mobile': '?0',
               'sec-ch-ua-platform': '"Windows"',
               'Sec-Fetch-Dest': 'empty',
               'Sec-Fetch-Mode': 'cors',
               'Sec-Fetch-Site': 'same-origin',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
               'userType': 'USER_RZ_ZIRANREN',
               }
    data = {"zhuanlisqh": application_number}
    patent_status_res = session.post(
        status_post_url, headers=headers, data=json.dumps(data))
    # print(patent_status_res)
    patent_status_res_json = patent_status_res.json()
    print(patent_status_res_json)
    print('===='*10)
    # 解析获取专利信息
    res_msg = patent_status_res_json.get('msg')
    if res_msg == '成功':
        patent_status_data = patent_status_res_json.get('data')
        item = dict()
        item['sqh'] = 'ZL' + application_number
        item["name"] = patent_status_data.get('zhuluxmxx').get('zhuluxmxx').get('zhuanlimc')
        if item["name"] == '--':
            redis_con.sadd('信合红谷接口查询', item['sqh'])
            return
        item["state"] = patent_status_data.get('zhuluxmxx').get('zhuluxmxx').get('anjianywzt')
        item["sq_date"] = patent_status_data.get('zhuluxmxx').get('zhuluxmxx').get('shenqingr')
        item['fm_class'] = patent_status_data.get('zhuluxmxx').get('zhuluxmxx').get('zhufenlh')
        try:
            dljg_info = patent_status_data.get('dailijg').get('dailijgList')[0]
            item["dljg"] = dljg_info.get('dailijgdm')
            item["dlr"] = dljg_info.get('diyidlrxm')
        except:
            item["dljg"] = ''
            item["dlr"] = ''

        famingrenList = patent_status_data.get('famingren').get('famingrenList')
        print("sqr_list: ", famingrenList)
        sqr_list = [line.get('famingrxm') for line in famingrenList]

        shenqingrenList = patent_status_data.get(
            'shenqingren').get('shenqingrenList')
        item["sqr"] = ','.join([line.get('shenqingrxm')
                                for line in shenqingrenList])
        item["fmr_name"] = ','.join(sqr_list)
        item['inst'] = inst
        print(item)
        print('====' * 10)
        sql = f"""INSERT INTO xhhg_pantent_status_0421 (application_number, case_status, fm_name, sq_date, created_at, updated_at, agency, patent_user, first_agent, fmr, port, fm_class) VALUES
            ('{item["sqh"]}', '{item["state"]}', '{item["name"]}',  '{item["sq_date"]}', NOW(), NOW(), '{item["dljg"]}', '{item["sqr"]}', '{item["dlr"]}', '{item["fmr_name"]}', '{item['inst']}', '{item['fm_class']}')"""
        try:
            cur.execute(sql)
            db.commit()
        except Exception as e:
            print(e)
            print(sql)
            time.sleep(1000)


def select_sqh():
    sql = 'SELECT application_number FROM xhhg_pantent_status_0421'
    cur.execute(sql)
    data = cur.fetchall()
    have_already_done = [sqh[0].replace("ZL", '') for sqh in data]
    return have_already_done


def run(port, authorization):
    session = requests.session()
    have_already_done = select_sqh()  # 获取数据库已经获取到专利数据的申请号
    redis_con = redis.Redis(host='121.4.69.146', password='xhhg123456',
                            port=6389, db=2, decode_responses=True)  # 连接redis数据库
    all_start_time = time.time()
    while redis_con.scard(port):
        start_time = time.time()
        sqh = redis_con.spop(port).replace("ZL", '')
        # if any([sqh not in i for i in have_already_done]):  # 跳过重复的申请号，
        print(sqh)
        get_patent_status(session, authorization, sqh, redis_con)
        end_time = time.time()
        print(f"本次耗时: {end_time - start_time}")
        need_time = round((end_time - start_time) *
                          redis_con.scard(port) / 60, 1)
        print(
            f"开始抓取'{sqh}'的信息， 剩余{redis_con.scard(port)}个，大约还需要{need_time}分钟")
        time.sleep(1)
    all_end_time = time.time()
    print(f"@@总耗时：{all_end_time - all_start_time}@@")


if __name__ == '__main__':
    # login_get_authorization()
    # with open('authorization.txt', 'r', encoding='utf-8') as file:
    #     authorization = file.readline().strip()
    #     print(authorization)
    port = "协和端口查询"
    session = requests.session()
    application_number = '2018209739169'
    authorization = 'Bearer eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJuZXVzb2Z0IiwiaWF0IjoxNjgyNDcxNDM3LCJleHAiOjE2ODI1MDAyMzcsImFjY2Vzc190b2tlbiI6IjJjMjJiOGM1LTIyNTUtNGNkMC1iMTMzLWIzMDk3ZDg3OGNjMCIsInJlZnJlc2hfdG9rZW4iOiIxMTlkYTQ4OS1hMjExLTQ5YjQtYTU3Ni1mZDUzM2YzOTJkYTgiLCJ1c2VySWQiOiIxNTYwMDk3OTI0MyIsIkV4cGlyZXNfaW4iOjI4ODAwfQ.ZchbzZtNkjNM5b0P3rrXo_S6Pz8TiAk9_3qW5PvLl3vEVxuA_yqf1xfWoBTXXp_D9vnJRozWX8GR3s-1sdHlCb3EvaLvdU9Nb4dCjd8P9T0zdtiQ7DfRxLThUtPi3KpnuN41Moj_SslmtuNH05kWLoatJBAuDPIBC9BDwqJy6ek'
    run(port, authorization)
    # get_patent_status(session, authorization, application_number)
    db.close()
